package com.gill.touka.auth;

import com.gill.touka.util.JwtOperator;
import io.jsonwebtoken.Claims;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 认证与授权切面类
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Component
@Aspect
public class AuthAspect {

    @Autowired
    private JwtOperator jwtOperator;

    /**
     * 校验请求是否携带token
     */
    @Around("@annotation(com.gill.touka.auth.CheckLogin)")
    public Object checkLogin(ProceedingJoinPoint point) throws Throwable {
        checkToken();
        return point.proceed();
    }

    /**
     * 校验token
     */
    private void checkToken(){
        try {
            // 1、获取header
            HttpServletRequest request = getHttpServletRequest();
            String token = request.getHeader("X-Token");
            // 2、校验token
            Boolean isValid = jwtOperator.validateToken(token);
            if(!isValid){
                throw new SecurityException("Token不合法");
            }
            // 3. 如果校验成功，那么就将用户的信息设置到request的attribute里面
            Claims claims = jwtOperator.getClaimsFromToken(token);
            request.setAttribute("id",claims.get("id"));
            request.setAttribute("wxNickname",claims.get("wxNickname"));
            request.setAttribute("role",claims.get("role"));
        } catch (Throwable throwable) {
            throw new SecurityException("Token不合法");//无论发生什么异常，都会抛出SecurityException
        }
    }

    /**
     * 获取Request
     */
    private HttpServletRequest getHttpServletRequest(){
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes attributes = (ServletRequestAttributes) requestAttributes;
        return attributes.getRequest();
    }


}
